package city.spring.modules.system.controller;

import city.spring.modules.system.entity.GroupEntity;
import city.spring.modules.system.entity.PermissionEntity;
import city.spring.modules.system.entity.RoleEntity;
import city.spring.modules.system.service.GroupService;
import city.spring.modules.system.service.PermissionService;
import city.spring.modules.system.service.RoleService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户组信息 控制器
 *
 * @author HouKunLin
 * @date 2020/3/22 0022 17:40
 */
@RestController
@RequestMapping("/group")
public class GroupController extends ApiController {
    private final GroupService groupService;
    private final RoleService roleService;
    private final PermissionService permissionService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<GroupEntity, ?>> entityOrderFields;

    public GroupController(GroupService groupService, RoleService roleService, PermissionService permissionService) {
        this.groupService = groupService;
        this.roleService = roleService;
        this.permissionService = permissionService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(GroupEntity::getId);
        entityOrderFields.add(GroupEntity::getTitle);
        entityOrderFields.add(GroupEntity::getRemarks);
        entityOrderFields.add(GroupEntity::getGmtCreate);
        entityOrderFields.add(GroupEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>用户组信息</strong> 列表
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'GROUP') or hasAnyAuthority('group.list')")
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, GroupEntity entity) {
        LambdaQueryChainWrapper<GroupEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>用户组信息</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'GROUP') or hasAnyAuthority('group.list')")
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, GroupEntity entity) {
        LambdaQueryChainWrapper<GroupEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<GroupEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        return success(page);
    }

    /**
     * 获取一个 <strong>用户组信息</strong>
     *
     * @param id 主键ID
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'GROUP') or hasAnyAuthority('group.info')")
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        GroupEntity entity = groupService.getGroupInfo(id, false, false);
        return success(entity);
    }

    /**
     * 添加一个 <strong>用户组信息</strong>
     *
     * @param entity 新增的信息
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'GROUP') or hasAnyAuthority('group.add')")
    @PostMapping
    public Object add(@RequestBody GroupEntity entity) {
        groupService.saveGroup(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, entity.getId());
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>用户组信息</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'GROUP') or hasAnyAuthority('group.update')")
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody GroupEntity entity) {
        entity.setId(id);
        groupService.updateGroup(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>用户组信息</strong>
     *
     * @param id 主键ID
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'GROUP') or hasAnyAuthority('group.delete')")
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        groupService.deleteGroup(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>用户组信息</strong>
     *
     * @param ids 主键ID列表
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'GROUP') or hasAnyAuthority('group.delete')")
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        groupService.deleteGroup(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 获取某个用户组的角色列表
     *
     * @param groupId 用户组ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','GROUP') or hasAnyAuthority('group.config-roles')")
    @GetMapping("{groupId}/roles")
    public Object getGroupRoles(@PathVariable String groupId) {
        return success(roleService.getGroupRoles(groupId));
    }

    /**
     * 设置某个用户组的角色列表（给用户组分配角色）
     *
     * @param groupId 用户组ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','GROUP') or hasAnyAuthority('group.config-roles')")
    @PutMapping("{groupId}/roles")
    public Object setGroupRoles(@PathVariable String groupId, @RequestBody List<RoleEntity> roleEntities) {
        GroupEntity entity = new GroupEntity();
        entity.setId(groupId);
        entity.setRoles(roleEntities);
        groupService.setGroupRoles(entity);

        return success(null);
    }

    /**
     * 获取某个用户组的权限列表
     *
     * @param groupId 用户组ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','GROUP') or hasAnyAuthority('group.config-permissions')")
    @GetMapping("{groupId}/permissions")
    public Object getGroupPermissions(@PathVariable String groupId) {
        return success(permissionService.getGroupPermissions(groupId));
    }

    /**
     * 设置某个用户组的权限列表（给用户组分配权限）
     *
     * @param groupId 用户组ID
     */
    @PreAuthorize("hasAnyRole('ADMIN','GROUP') or hasAnyAuthority('group.config-permissions')")
    @PutMapping("{groupId}/permissions")
    public Object setGroupPermissions(@PathVariable String groupId, @RequestBody List<PermissionEntity> permissionEntities) {
        GroupEntity entity = new GroupEntity();
        entity.setId(groupId);
        entity.setPermissions(permissionEntities);
        groupService.setGroupPermissions(entity);

        return success(null);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<GroupEntity> buildLambdaQuery(GroupEntity entity) {
        LambdaQueryChainWrapper<GroupEntity> lambdaQuery = groupService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), GroupEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTitle()), GroupEntity::getTitle, entity.getTitle());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRemarks()), GroupEntity::getRemarks, entity.getRemarks());
        return lambdaQuery;
    }
}
